 # Provide multipart/form-data for http

 package provide form-data 1.0
 package require mime

 namespace eval form-data {}

 proc form-data::compose {partv {type multipart/form-data}} {
     upvar 1 $partv parts

     set mime [mime::initialize -canonical $type -parts $parts]
     set packaged [mime::buildmessage $mime]
     foreach part $parts {
 	mime::finalize $part
     }
     mime::finalize $mime

     return $packaged
 }

 proc form-data::add_binary {partv name filename value type} {
     upvar 1 $partv parts
     set disposition "form-data; name=\"${name}\"; filename=\"$filename\""
     lappend parts [mime::initialize -canonical $type \
 		   -string $value \
 		   -encoding binary \
 		   -header [list Content-Disposition $disposition]]
 }

 proc form-data::add_field {partv name value} {
     upvar 1 $partv parts
     set disposition "form-data; name=\"${name}\""
     lappend parts [mime::initialize -canonical text/plain -string $value \
 		       -header [list Content-Disposition $disposition]]
 }

 proc form-data::format {name filename value type args} {
     set parts {}
     foreach {n v} $args {
 	add_field parts $n $v
     }
     add_binary parts $name $filename $value $type
     return [compose parts]
 }
